<template>
	<view>
		<view class="header">
			<text class="title">{{ title }}</text>
		</view>

		<button class="add-button" @click="addDay">新增一天作业</button>
		<view v-for="(day, dayIndex) in assignments" :key="dayIndex">
			<view class="assignment-header" @click="toggleDay(dayIndex)">
				{{ `第 ${dayIndex + 1} 天作业` }}
			</view>
			<view v-if="expandedDayIndex === dayIndex" class="assignment-content">
				<button @click="addAssignmentToDay(dayIndex)">新增当天作业</button>
				<view v-for="(assignment, assignmentIndex) in day" :key="assignmentIndex">
					<picker mode="selector" :range="typeOptions" :value="assignment.typeIndex"
						@change="(e) => changeAssignmentType(dayIndex, assignmentIndex, e.detail.value)">
						<view class="picker">{{ typeOptions[assignment.typeIndex] }}</view>
					</picker>
					<input v-model="assignment.title" placeholder="请输入作业标题" class="input-field" />
					<template v-if="assignment.type === '1' || assignment.type === '3'">
						<textarea  :maxlength="5000"  v-model="assignment.content" placeholder="请输入作业内容" class="textarea-field"></textarea>
					</template>
					<template v-if="assignment.type === '2'">
						<button @click="uploadVideo(dayIndex, assignmentIndex)">上传视频</button>
						<span v-if="assignment.content">{{ assignment.content }}</span>
					</template>
					<button class="delete-button" @click="deleteAssignment(dayIndex, assignmentIndex)">删除</button>
				</view>
			</view>
		</view>
		<button class="save-button" @click="reportError">保存</button>
	</view>
</template>

<script>
	export default {
		onLoad(options) {
			this.classId = options.classId;
			this.sessionNumber = options.sessionNumber;
			this.title = options.title;
			this.getWork();
		},
		data() {
			return {
				classId: null,
				sessionNumber: null,
				expandedDayIndex: -1,
				title: '',
				content: '',
				readOnly: false,
				formats: {},
				assignments: [],
				typeOptions: ['任务', '视频', '长文本'],
				typeValueMap: {
					0: '1',
					1: '2',
					2: '3'
				},
				selectedTypeIndex: 0
			};
		},
		methods: {
			getWork() {
				const type = this.selectedTypeIndex === 0 ? null : this.typeValueMap[this.selectedTypeIndex];
				uni.request({
					url: 'http://localhost:9090/user/getWork',
					method: 'POST',
					data: {
						classId: this.classId,
						sessionNumber: this.sessionNumber,
						type: type
					},
					success: (res) => {
						const groupedAssignments = [];
						res.data.data.forEach(item => {
							const day = item.days - 1; // 因为数组索引从 0 开始
							if (!groupedAssignments[day]) {
								groupedAssignments[day] = [];
							}
							const typeIndex = Object.keys(this.typeValueMap).find(key => this
								.typeValueMap[key] === item.type);
							groupedAssignments[day].push({
								...item,
								typeIndex: parseInt(typeIndex)
							});
						});
						this.assignments = groupedAssignments.filter(Boolean); // 过滤掉可能存在的空数组
					},
					fail: (err) => {
						console.error('获取资源失败:', err);
					}
				});
			},
			toggleDay(dayIndex) {
				if (this.expandedDayIndex === dayIndex) {
					this.expandedDayIndex = -1;
				} else {
					this.expandedDayIndex = dayIndex;
				}
			},
			addDay() {
				this.assignments.push([{
					title: '',
					content: '',
					type: '1',
					typeIndex: 0,
					videoUrl: ''
				}]);
			},
			addAssignmentToDay(dayIndex) {
				this.assignments[dayIndex].push({
					title: '',
					content: '',
					type: '1',
					typeIndex: 0,
					videoUrl: ''
				});
			},
			deleteAssignment(dayIndex, assignmentIndex) {
				this.assignments[dayIndex].splice(assignmentIndex, 1);
				if (this.assignments[dayIndex].length === 0) {
					this.assignments.splice(dayIndex, 1);
				}
			},
			changeAssignmentType(dayIndex, assignmentIndex, newIndex) {
				this.assignments[dayIndex][assignmentIndex].typeIndex = newIndex;
				this.assignments[dayIndex][assignmentIndex].type = this.typeValueMap[newIndex];
				if (this.assignments[dayIndex][assignmentIndex].type === '2') {
					this.assignments[dayIndex][assignmentIndex].content = '';
				}
			},
			uploadVideo(dayIndex, assignmentIndex) {
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60,
					camera: 'back',
					success: (res) => {
						const maxSize = 50 * 1024 * 1024; // 50M 换算为字节
						if (res.size > maxSize) {
							uni.showToast({
								title: '视频大小不能超过 50M',
								icon: 'none'
							});
							return;
						}
						const tempFilePath = res.tempFilePath;
						// 显示加载提示
						uni.showLoading({
							title: '上传中...',
							mask: true
						});
						uni.uploadFile({
							url: 'http://localhost:9090/file/upload',
							filePath: tempFilePath,
							name: 'file',
							success: (uploadRes) => {
								// 隐藏加载提示
								uni.hideLoading();
								if (uploadRes.statusCode === 200) {
									// 弹出上传成功提示框
									uni.showToast({
										title: '上传成功',
										icon: 'success'
									});
									// 将视频地址存放在当天作业的content字段中
									this.assignments[dayIndex][assignmentIndex].content = uploadRes
										.data;
								} else {
									// 弹出上传失败提示框
									uni.showToast({
										title: '上传失败',
										icon: 'none'
									});
								}
							},
							fail: (err) => {
								// 隐藏加载提示
								uni.hideLoading();
								console.error('上传出错:', err);
								// 弹出上传出错提示框
								uni.showToast({
									title: '上传出错',
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('选择视频失败:', err);
					}
				});
			},
			reportError() {
				for (let dayIndex = 0; dayIndex < this.assignments.length; dayIndex++) {
					const day = this.assignments[dayIndex];
					for (let assignmentIndex = 0; assignmentIndex < day.length; assignmentIndex++) {
						const assignment = day[assignmentIndex];
						if (!assignment.title || assignment.title.trim() === '') {
							let dayNum = dayIndex + 1;
							let assignmentNum = assignmentIndex + 1;
							uni.showToast({
								title: `第${dayNum}天第${assignmentNum}个作业标题不能为空`,
								icon: 'none'
							});
							return;
						}
						if (assignment.type === '1' || assignment.type === '3') {
							if (!assignment.content || assignment.content.trim() === '<p></p>') {
								let dayNum = dayIndex + 1;
								let assignmentNum = assignmentIndex + 1;
								uni.showToast({
									title: `第${dayNum}天第${assignmentNum}个作业内容不能为空`,
									icon: 'none'
								});
								return;
							}
						} else if (assignment.type === '2' && !assignment.content) {
							let dayNum = dayIndex + 1;
							let assignmentNum = assignmentIndex + 1;
							uni.showToast({
								title: `第${dayNum}天第${assignmentNum}个作业视频未上传`,
								icon: 'none'
							});
							return;
						}
					}
				}

				const formattedAssignments = this.assignments.map((day, dayIndex) => {
					return day.map(assignment => ({
						...assignment,
						days: dayIndex + 1
					}));
				});

				const formData = {};
				uni.request({
					url: 'http://localhost:9090/user/setWork',
					method: 'POST',
					data: {
						classId: this.classId,
						sessionNumber: this.sessionNumber,
						assignments: formattedAssignments.flat()
					},
					success: (res) => {
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						});
						// uni.switchTab({
						//     url: '/pages/mine/index',
						//     success() {},
						//     fail(err) {}
						// });
						this.getWork()
					},
					fail: (err) => {
						console.error('保存失败:', err);
					}
				});
			},
			onTypeChange(e) {
				this.selectedTypeIndex = e.detail.value;
				this.getWork();
			}
		}
	};
</script>

<style>
	@import "editor-icon.css";

	.header {
		padding: 10px;
		border-bottom: 1px solid #eee;
	}

	.title {
		font-family: KaiTi;
	}

	.assignment-header {
		padding: 20px;
		border-bottom: 1px solid #eee;
		cursor: pointer;
	}

	.assignment-content {
		padding: 10px 20px;
		border-bottom: 1px solid #eee;
		/* 确保编辑器有足够的高度 */
		min-height: 200px;
	}

	button {
		margin: 5px;
	}

	.add-button {
		background-color: green;
		color: white;
	}

	.delete-button {
		background-color: red;
		color: white;
	}

	.save-button {
		background-color: blue;
		color: white;
	}

	.editor-wrapper {
		height: 600rpx;
		background: #fff;
	}

	.iconfont {
		flex: 0 0 10%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
		display: flex;
		flex-wrap: wrap;
	}

	.ql-container {
		box-sizing: border-box;
		font-size: 28rpx;
		line-height: 1.5;
		height: 100%;
	}

	.ql-active {
		color: #06c;
	}

	.input-field,
	.textarea-field {
		width: 100%;
		margin-bottom: 10px;
		padding: 5px;
		border: 1px solid #ccc;
		border-radius: 3px;
	}

	.picker {
		padding: 10px;
		border: 1px solid #ccc;
		margin: 10px 0;
	}
</style>